package com.hzk.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzk.pojo.UserBasic;
import com.hzk.utils.IpUtil;
import com.hzk.vo.RespBean;
import com.hzk.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @auoter:jackh
 */
@Component
//拦截器实现分布式token和接口限流
//拦截器的优先级高于interceptor
public class AccessLimitintercepter implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        UserBasic user = getUser(request, response);
        UserContext.setUser(user);//扔进线程里面
        HandlerMethod hm = (HandlerMethod) handler;
        RequireLogin methodAnnotation = hm.getMethodAnnotation(RequireLogin.class);
        if (methodAnnotation == null) {
            return true;
        }

        int seconds = methodAnnotation.seconds();
        int maxCount = methodAnnotation.maxCount();
        boolean needLogin = methodAnnotation.needLogin();

        String key = request.getRequestURI() + IpUtil.getIpAddress(request);
        if (needLogin) {
            if (user == null) {
                render(response, RespBeanEnum.NULL_USER_ERROR);
                return false;
            }
            key += ":" + user.getId();
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();

        Integer count = (Integer) valueOperations.get(key);
        if (count == null) {
            valueOperations.set(key, 1, seconds, TimeUnit.SECONDS);
        } else if (count < maxCount) {
            valueOperations.increment(key);
        } else {
            render(response, RespBeanEnum.p_ERROR);
            return false;
        }

        /*}*/
        return true;
    }

    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        RespBean bean = RespBean.error(respBeanEnum);
        out.write(new ObjectMapper().writeValueAsString(bean));
        out.flush();
        out.close();
    }

    private UserBasic getUser(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return null;
        }
        UserBasic user = (UserBasic) redisTemplate.opsForValue().get("UserBasic:" + token);
        if (user == null) {
            return null;
        }
        return user;
    }
}




